﻿using System;
using System.Collections.Generic;
using System.Linq;
using FL.Common;
using FL.DBModule;
using FL.DBModule.Sys;
using FL.DAL;
using FL.RuleEngine.Core;
using System.Data;

using System.Data.Entity;

namespace FL.Bussiness
{
    /// <summary>
    /// BllBase 的摘要说明。
    /// </summary>
    public  class BaseBussnies
    {

        public BaseBussnies(BaseEntity entitys)
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
            entity = entitys;
        }

        public BaseEntity entity
        {
            get;
            set;
        }

        
        public BaseBussnies CreateBussniess(string entityName)
        {
            return BaseBussnies.CreateInstance(entityName);
        }

        public BaseBussnies CreateBussniess()
        {
            return BaseBussnies.CreateInstance(this.entity.GetType().Name);
        }

        public BaseBussnies() { }

        /// <summary>
        /// 新增实体数据
        /// </summary>
        /// <param name="entitys">实体</param>
        public virtual bool Insert(object entitys)
        {
            FL.SPL.Factory.DialectFactory DF = FL.SPL.Factory.Dialects.GetDialect(entitys);
            return DF.Save();
            //DataContext.Entry(entitys);
            //return DataContext.SaveChanges()>0;
        }

        public virtual bool Insert(object entitys, out string msg)
        {
            msg = "";
            try
            {
                return Insert(entitys);
            }
            catch (Exception e)
            {
                msg = e.Message;
                return false;
            }
        }

        
        /// <summary>
        /// 新增实体数据
        /// </summary>
        public virtual  bool Insert()
        {
            return Insert(entity);
        }

        public virtual void afterInsert(){
        }

        public virtual bool Insert(out string msg)
        {
            return Insert(entity, out msg);
        }
        /// <summary>
        /// 更新实体数据
        /// </summary>
        /// <param name="entitys">实体</param>
        public virtual bool Update(object entitys)
        {
            FL.SPL.Factory.DialectFactory DF = FL.SPL.Factory.Dialects.GetDialect(entitys);
            return DF.Update();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="entitys"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public virtual bool Update(object entitys, out string msg)
        {
            msg = "";
            try
            {
                return Update(entitys);
            }
            catch (Exception e)
            {
                msg = e.Message;
                return false;
            }
        }


        /// <summary>
        /// 更新实体数据
        /// </summary>
        public virtual bool Update()
        {
            return Update(entity);
        }

        public virtual bool Update(out string msg)
        {
            return Update(entity,out msg);
        }


        /// <summary>
        /// 删除实体的数据
        /// </summary>
        /// <param name="entitys">实体</param>
        public virtual bool delete(object entitys)
        {
            FL.SPL.Factory.DialectFactory DF = FL.SPL.Factory.Dialects.GetDialect(entitys);
            return DF.Delete();
        }

        public virtual bool delete(object entitys,out string msg)
        {
            msg = "";
            try
            {
                return delete(entitys);
            }
            catch (Exception e)
            {
                msg = e.Message;
                return false;
            }
        }
        /// <summary>
        /// 删除实体的数据
        /// </summary>
        public virtual bool delete()
        {
            return delete(entity);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="condition">条件</param>
        /// <returns></returns>
        public virtual bool delete(string condition)
        {
            FL.SPL.Factory.DialectFactory DF = FL.SPL.Factory.Dialects.GetDialect(entity);
            return DF.Delete(condition);
        }


        /// <summary>
        /// 通过ID获取实体
        /// </summary>
        /// <param name="id">记录ID</param>
        /// <returns>实体</returns>
        public virtual  BaseEntity GetEntityById(string id)
        {
            if (id == "" || id == null)
            {
                return null;
            }
            else
            {
                try
                {
                    FL.SPL.Factory.DialectFactory df = FL.SPL.Factory.Dialects.GetDialect(this.entity);
                    string _strSel = df.SelectCommand(id);
                    return GetEntityBySqlComm(_strSel) as BaseEntity;
                }
                catch
                {
                    return null;
                }
            }
        }


        /// <summary>
        /// 数据操作日志
        /// </summary>
        public virtual void WriteDataLog(){

        }

        public virtual void WriteImportLog()
        {

        }

        /// <summary>
        /// 根据不同实体实例化业务实例
        /// 用于实现的不同的实体调用不同的业务逻辑
        /// </summary>
        /// <param name="entityName"></param>
        /// <returns></returns>
        public static BaseBussnies CreateInstance(string entityName)
        {
            t_set_entity entity = (new BaseBussnies()).GetEntityByCondition<t_set_entity>("name='" + entityName + "'");
            if (entity != null)
            {
                if (entity.bussiness_config != null)
                {
                    try
                    {
                        string[] str = entity.bussiness_config.Split(',');
                        return Common.Reflection.CreateInstance(str[0], str[1]) as BaseBussnies;
                    }
                    catch { }
                }
            }
            return new BaseBussnies();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual T GetEntityById<T>(int id)
        {
            BaseEntity be = default(T) as BaseEntity;
            return GetEntityByCondition<T>(be.GetTableKeyField() + "=" + id);
        }





        /// <summary>
        /// 通过SqlComm命令获取实体
        /// </summary>
        /// <param name="SqlComm">Sql Command</param>
        /// <returns>实体</returns>
        public virtual object GetEntityBySqlComm(string SqlComm)
        {
            if (SqlComm == null || SqlComm == string.Empty)
            {
                return null;
            }
            else
            {
                try
                {
                    FL.SPL.ORM.ObjectMapper om = new FL.SPL.ORM.ObjectMapper(entity);
                    om.SqlComm = SqlComm;
                    return om.DataTableToObject();
                }
                catch
                {
                    return null;
                }
            }
        }

        public virtual T GetEntityById<T>(Guid id)
        {
            BaseEntity be = Activator.CreateInstance<T>() as BaseEntity;
            return GetEntityByCondition<T>(be.GetTableKeyField() + "='" + id.ToString() + "'");
        }

        public virtual T GetEntityBySqlComm<T>(string SqlComm)
        {
            if (SqlComm == null || SqlComm == string.Empty)
            {
                return default(T);
            }
            else
            {
                try
                {
                    object o;
                    o = System.Activator.CreateInstance<T>();
                    FL.SPL.ORM.ObjectMapper om = new FL.SPL.ORM.ObjectMapper(o,SqlComm);
                    om.SqlComm = SqlComm;
                    return (T)om.DataTableToObject();
                }
                catch
                {
                    return default(T);
                }
            }
        }


        /// <summary>
        /// 获取插入更新的Sql Command
        /// </summary>
        /// <param name="entity">实体类</param>
        /// <returns></returns>
        public virtual string GetSqlCommand(BaseEntity entity)
        {
            FL.SPL.Factory.DialectFactory DF = FL.SPL.Factory.Dialects.GetDialect(entity);
            return DF.GetSqlCommand();
        }

        /// <summary>
        /// 通过SqlComm命令获取实体
        /// </summary>
        /// <param name="SqlComm">Sql Command</param>
        /// <returns>实体</returns>
        public virtual IList<BaseEntity> GetEntitysBySqlComm(string SqlComm)
        {
            if (SqlComm == null || SqlComm == string.Empty)
            {
                return null;
            }
            else
            {
                try
                {
                    SqlComm = iTop > 0 ? SqlComm.ToLower().Replace("select", "select top " + iTop.ToString()) : SqlComm;
                    string order = this.Order == "" || this.Order == null ? "" : " Order by " + this.Order;
                    //order = order == "" ? " " : order + (this.Desc == "Yes" ? "  Desc " : " Asc");
                    FL.SPL.ORM.ObjectMapper om = new FL.SPL.ORM.ObjectMapper(entity);

                    om.SqlComm = SqlComm + " " + order;
                    return om.DatatableToObject();
                }
                catch (System.Exception ex)
                {
                    return null;
                }
            }
        }


        public virtual IList<T> GetEntitysBySqlComm<T>(string SqlComm)
        {
            if (SqlComm == null || SqlComm == string.Empty)
            {
                return null;
            }
            else
            {
                try
                {
                    SqlComm = iTop > 0 ? SqlComm.ToLower().Replace("select", "select top " + iTop.ToString()) : SqlComm;
                    string order = this.Order == "" || this.Order == null ? "" : " Order by " + this.Order;
                    //order = order == "" ? " " : order + (this.Desc == "Yes" ? " Desc " : " Asc");
                    FL.SPL.ORM.TObject<T> om = new FL.SPL.ORM.TObject<T>(SqlComm);
                    om.SqlComm = SqlComm + " " + order;
                    return om.DatatableToObject<T>();
                }
                catch (System.Exception ex)
                {
                    return null;
                }
            }
        }


        public IList<TableInfoStruc> GetTableInfoStruc(string tableName)
        {
            return this.GetEntitysBySqlComm<TableInfoStruc>("select * from V_TableInfoStruc where +TableName='" + tableName + "'");
        }

        public string GetTableKey(string tableName)
        {
            IList < TableInfoStruc> list  = this.GetEntitys<TableInfoStruc>("TableName='" + tableName + "' and Substring(PKey,1,1)='Y'");
         
            if (list == null)
            {
                if (tableName.IndexOf('.') > 0)
                {
                    return this.GetEntitys<t_set_datagrid>("entity='" + tableName.Split('.')[1] + "'").First().name;
                }
                else
                {
                    return this.GetEntitys<t_set_datagrid>("entity='" + tableName + "'").First().name;
                }
            }
            return (list.First() == null) ? "ID" : list.First().ColName;
        }

        public virtual System.Data.DataTable GetDTByTable(string tableName)
        {
            FL.SPL.ORM.ObjectMapper om = new SPL.ORM.ObjectMapper(null);
            return om.GetDataTableByTableName(tableName);
            //FL.SPL.ORM.ObjectMapper om = new SPL.ORM.ObjectMapper(this.entity);
            //return om.GetDataBySqlComm();
        }

        public virtual System.Data.DataTable GetDataBySqlComm(string SqlComm)
        {
            if (SqlComm == null || SqlComm == string.Empty)
            {
                return null;
            }
            else
            {
                try
                {
                    FL.SPL.ORM.ObjectMapper om = new FL.SPL.ORM.ObjectMapper(entity);
                    om.SqlComm = SqlComm;
                    return om.GetDataBySqlComm();
                }
                catch
                {
                    return null;
                }
            }
        }

        public virtual System.Data.DataTable GetDTStuceByTable(string tableName)
        {
            FL.SPL.ORM.ObjectMapper om = new SPL.ORM.ObjectMapper(null);
            return om.GetDTStrucByTableName(tableName);
        }


        public virtual IList<BaseEntity> GetEntitysSplitPage(string Condition)
        {
            this.Order = (this.Order == "" ? this.entity.getKey() : this.Order);
            string SqlComm = string.Empty;
            try
            {
                //2012-11-16：15：33添加RowNumber排序
                string order = string.IsNullOrEmpty(this.Order) ? "" : "( Order by " + this.Order +" ) ";
                //order = string.IsNullOrEmpty(order) ? " " : order + (this.Desc == "Yes" ? " Desc) " : " Asc) ");
                SqlComm = "SELECT TOP " + PageSize.ToString() + " * FROM  (  SELECT ROW_NUMBER() OVER" + order + " AS RowNumber,* FROM " + this.entity.getTableName() + (string.IsNullOrEmpty(Condition) ? "" : " where " + Condition) + ") A WHERE RowNumber > " + (PageIndex - 1) * PageSize + " order by RowNumber";
                //SqlComm = iTop > 0 ? SqlComm.ToLower().Replace("select", "select top " + PageSize.ToString()) : SqlComm;
                FL.SPL.ORM.ObjectMapper om = new SPL.ORM.ObjectMapper(this.entity);
                om.SqlComm = SqlComm;
                return om.DatatableToObject();
            }
            catch (System.Exception ex)
            {
                return null;
            }
        }


        ///// <summary>
        ///// 
        ///// </summary>
        ///// <param name="sql"></param>
        ///// <param name="Condition"></param>
        ///// <returns></returns>
        //public virtual DataTable GetEntitysSplitPageBySql(string sql,string Condition)
        //{
        //    this.Order = (this.Order == "" ? this.entity.getKey() : this.Order);
        //    string SqlComm = string.Empty;
        //    try
        //    {
        //        //2012-11-16：15：33添加RowNumber排序
        //        string order = string.IsNullOrEmpty(this.Order) ? "" : "( Order by " + this.Order + " ) ";
        //        //order = string.IsNullOrEmpty(order) ? " " : order + (this.Desc == "Yes" ? " Desc) " : " Asc) ");
        //        SqlComm = "SELECT TOP " + PageSize.ToString() + " * FROM  (  SELECT ROW_NUMBER() OVER" + order + " AS RowNumber,* FROM (" + this.entity.getTableName() +") as target_table "+ (string.IsNullOrEmpty(Condition) ? "" : " where " + Condition) + ") A WHERE RowNumber > " + (PageIndex - 1) * PageSize + " order by RowNumber";
        //        //SqlComm = iTop > 0 ? SqlComm.ToLower().Replace("select", "select top " + PageSize.ToString()) : SqlComm;
        //        FL.SPL.ORM.ObjectMapper om = new SPL.ORM.ObjectMapper(this.entity);
        //        om.SqlComm = SqlComm;
        //        return om.GetDataBySqlComm();
        //    }
        //    catch (System.Exception ex)
        //    {
        //        return null;
        //    }
        //}


        public int GetRowCount(string Condition)
        {
            return (new FL.DAL.DbSql()).GetRowCount(this.entity.GetTableName(), Condition);
        }

        public int GetRowCount(string sql, string Condition)
        {
            return (new FL.DAL.DbSql()).GetSqlRowCount(sql, Condition);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="Condition"></param>
        /// <returns></returns>
        public virtual System.Data.DataTable GetDataTableSplitPage(string sql, string Condition)
        {
            this.Order = (this.Order == "" ? this.entity.getKey() : this.Order);
            string SqlComm = string.Empty;
            try
            {
                string order = string.IsNullOrEmpty(this.Order) ? "" : "( Order by " + this.Order + "  ";
                if (!order.Contains(",") && !order.ToLower().Contains("desc") && !order.ToLower().Contains("asc"))
                {
                    order = string.IsNullOrEmpty(order) ? "" : order + (this.Desc == "Yes" ? " Desc) " : " Asc) ");
                }
                if (order == "")
                {
                    order = "(order by id desc) ";
                }
                if (!order.Contains(")"))
                {
                    order = order + ") ";
                }
                SqlComm = "SELECT TOP " + PageSize.ToString() + " * FROM  (SELECT ROW_NUMBER() OVER" + order + " AS RowNumber,* FROM (" + sql + ") as target_table" + (string.IsNullOrEmpty(Condition) ? "" : " where " + Condition) + ") A WHERE RowNumber > " + (PageIndex - 1) * PageSize + " order by rowNumber";
                //SqlComm = iTop > 0 ? SqlComm.ToLower().Replace("select", "select top " + PageSize.ToString()) : SqlComm;
                FL.SPL.ORM.ObjectMapper om = new SPL.ORM.ObjectMapper(this.entity);
                om.SqlComm = SqlComm;
                return om.GetDataBySqlComm();
            }
            catch (System.Exception ex)
            {
                return null;
            }
        }
        
        public virtual IList<BaseEntity> GetEntitysByCondition(string Condition)
        {
            FL.SPL.Factory.DialectFactory df = FL.SPL.Factory.Dialects.GetDialect(entity);
            return GetEntitysBySqlComm(df.SelectAllCommand() + " where " + Condition);
        }


        public System.Data.DataTable CreateDataTable(string tableName)
        {
            IList<TableInfoStruc> tfList = GetTableInfoStruc(tableName);
            System.Data.DataTable dt = new System.Data.DataTable();
            foreach (TableInfoStruc tifs in tfList)
            {
                dt.Columns.Add(tifs.TableName, FL.Common.Globals.CovertDBType(tifs.CType));
            }
            return dt;
        }

        public System.Data.DataTable CreateDataTable(string tableName,out IList<TableInfoStruc> tf)
        {
            IList<TableInfoStruc> tfList = GetTableInfoStruc(tableName);
            System.Data.DataTable dt = new System.Data.DataTable();
            foreach (TableInfoStruc tifs in tfList)
            {
                dt.Columns.Add(tifs.ColName, FL.Common.Globals.CovertDBType(tifs.CType));
            }
            tf = tfList;
            return dt;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <param name="Json"></param>
        /// <returns></returns>
        public virtual System.Data.DataTable GetSingleRowDT(string tableName, string Json)
        {
            Dictionary<string, object> JsonData = FL.Common.Globals.ConvertToDictionary(Json);
            IList<TableInfoStruc> tf;
            System.Data.DataTable dt = CreateDataTable(tableName,out tf);
            System.Data.DataRow dr = dt.NewRow();
            foreach (KeyValuePair<string, object> field in JsonData)
            {
                string FType = tf.Where(p => p.ColName == field.Key).Select(p => p.CType).FirstOrDefault();
                dr[field.Key] = FL.Common.Globals.CovertValue(FType,field.Value as string);
            }
            dt.Rows.Add(dr);
            return dt;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public virtual IList<BaseEntity> GetEntitys()
        {
            FL.SPL.Factory.DialectFactory df = FL.SPL.Factory.Dialects.GetDialect(this.entity);
            return this.GetEntitysBySqlComm(df.SelectAllCommand());
        }


        public virtual IList<T> GetEntitys<T>()
        {
            FL.SPL.Factory.DialectFactory df = FL.SPL.Factory.DialectFactory.instance<T>();
            return this.GetEntitysBySqlComm<T>(df.SelectAllCommand());
        }
      
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Condition"></param>
        /// <returns></returns>
        public virtual IList<BaseEntity> GetEntitys(string Condition)
        {
            if (Condition == null || Condition == string.Empty)
            {
                return GetEntitys();
            }
            else
            {
                FL.SPL.Factory.DialectFactory df = FL.SPL.Factory.Dialects.GetDialect(entity);
                IList<BaseEntity> entitys= this.GetEntitysBySqlComm(df.SelectAllCommand() + " where " + Condition);
                return entitys;
            }
        }
        public virtual IList<T> GetEntitys<T>(string Condition)
        {
            if (Condition == null || Condition == string.Empty)
            {
                return GetEntitys<T>();
            }
            else
            {
                FL.SPL.Factory.DialectFactory df = FL.SPL.Factory.DialectFactory.instance<T>();
                return this.GetEntitysBySqlComm<T>(df.SelectAllCommand() + " where " + Condition);
            }
        }
        /// <summary>
        /// 生成XML文件
        /// </summary>
        /// <param name="SqlComm"></param>
        /// <returns></returns>
        public virtual string BuildXmlFile(string SqlComm)
        {
            FL.SPL.ORM.ObjectMapper om = new FL.SPL.ORM.ObjectMapper(new object(), SqlComm);
            return om.BuildXmlFile();
        }
        /// <summary>
        /// 数据实体数组
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual IList<BaseEntity> GetEntitysByIds(string[] id)
        {
            if (id.Length == 0)
            {
                return null;
            }

            IList<BaseEntity> al = new List<BaseEntity>();
            for (int i = 0; i < id.Length - 1; i++)
            {
                BaseEntity obj = GetEntityById(id[i]);
                al.Add(obj);
            }
            return al;
        }


        //public IList<T> GetEntitysByIds<T>(string[] id)
        //{
        //    if (id.Length == 0)
        //    {
        //        return null;
        //    }

        //    ArrayList al = new ArrayList();
        //    for (int i = 0; i < id.Length - 1; i++)
        //    {
        //        object obj = GetEntityById(id[i]);
        //        al.Add(obj);
        //    }
        //    return al.ToArray();
        //}
        /// <summary>
        /// 通过条件获取实体
        /// </summary>
        /// <param name="Condition">条件</param>
        /// <returns>实体</returns>
        public virtual object GetEntityByCondition(string Condition)
        {
            FL.SPL.Factory.DialectFactory df = FL.SPL.Factory.Dialects.GetDialect(entity);
            return this.GetEntityBySqlComm(df.SelectAllCommand() + " where " + Condition);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Condition"></param>
        /// <returns></returns>
        public virtual T GetEntityByCondition<T>(string Condition)
        {
            FL.SPL.Factory.DialectFactory df = FL.SPL.Factory.DialectFactory.instance<T>();
            return this.GetEntityBySqlComm<T>(df.SelectAllCommand() + " where " + Condition);
        }
       
        [Obsolete("不要再override此方法了",false)]
        public virtual string CheckData(BaseEntity entity)
        {
            if (entity == null)
            {
                return CheckData();
            }
            string msg = RunScript(entity, null);
            if (string.IsNullOrEmpty(msg))
            {
                return CheckData();
            }
            return msg;
        }

        /// <summary>
        /// 数据检查，用于页面调用自定义
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        public virtual string CheckData(BaseEntity entity,object page)
        {
            string msg="";
            try
            {
                msg = RunScript(entity, page);
            }
            catch { return msg; }
            return msg;
        }


        public string RunScript(BaseEntity entity, object page)
        {
            t_set_entity _entity = null;
            if (entity is DataTableBaseEntity)
            {
                _entity = this.GetEntityByCondition<t_set_entity>("name='" + this.entity.GetTableName() + "'");
            }
            else
            {
                _entity = this.GetEntityByCondition<t_set_entity>("name='" + this.entity.GetType().Name + "'");
            }

            if (_entity == null)
                return "";
            if (string.IsNullOrEmpty(_entity.role_script))
                return "";
            string _script = @"msg='';
                               function check(e){
                                    {0}
                                   }
                               func = check;
                               msg = func(entity);
                               ".Replace("{0}", _entity.role_script).Replace("[B]", "'");
            string msg = RoleRuntimeHost.CheckData(this.entity, _script, page);
            return msg;
        }


        public virtual string CheckData() 
        { 
            return ""; 
        }

        public virtual string EditCheckData()
        {
            return "";
        }

        public virtual string DeleteCheckData()
        {
            return "";
        }



        /// <summary>
        /// 
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="DataType"></param>
        /// <returns></returns>
        public bool isEmpty(object obj, string DataType)
        {
            if (obj == null)
            {
                return true;
            }

            if (DataType.IndexOf("String") == 0)
            {
                if ((string)obj == string.Empty)
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 获取唯一标识符
        /// </summary>
        /// <returns></returns>
        public string GetKeyField()
        {
            if (this.entity is DataTableBaseEntity)
            {
                DataTableBaseEntity table = ((DataTableBaseEntity)this.entity);
                if(!string.IsNullOrEmpty(((DataTableBaseEntity)this.entity).KeyField))
                {
                    return table.KeyField;
                }
                else
                {
                    //TableInfoStruc entity = this.GetEntityByCondition<TableInfoStruc>("TableName='"+table.TableName+"' and Substring(PKey,1,1)='Y'");
                    TableInfoStruc entity = this.GetEntityByCondition<TableInfoStruc>("TableName='"+table.TableName+"' and sort='1'");
                    if (entity == null)
                    {
                        this.Order = "sort";
                        this.Desc = "No";
                        return this.GetEntitys<t_set_datagrid>("entity='" + table.TableName + "'").First().name;
                    }
                    return entity.ColName;
                }
            }
            else
            {
                Type t = this.entity.GetType();
                foreach (Attribute attr in t.GetCustomAttributes(true))
                {
                    FL.DBModule.TableAttribute tableattribute = attr as FL.DBModule.TableAttribute;
                    if (null != tableattribute)
                    {
                        return tableattribute.Guid;
                    }
                }
                return "";
            }
        }

        /// <summary>
        /// 获取Key信息
        /// </summary>
        /// <returns></returns>
        public string[] GetKey()
        {
            return this.GetKey(this.entity.getTableName());
        }


        public string[] GetKey(string tableName)
        {
            string[] str = new string[2];
            TableInfoStruc entity = this.GetEntityByCondition<TableInfoStruc>("TableName='" + tableName + "' and Substring(PKey,1,1)='Y'");
            if (entity == null)
            {
                entity = this.GetEntityByCondition<TableInfoStruc>("TableName='" + tableName + "' and sort=1");

            }
            if (entity != null)
            {
                str[0] = entity.ColName;
                str[1] = entity.CType;
            }
            return str;
        }


        /// <summary>
        /// 分页
        /// </summary>
        /// <returns></returns>
        public virtual IList<BaseEntity> GetEntitysSplitPage()
        {
                string SqlComm=string.Empty;
                try
                {
                    string order = this.Order == "" || this.Order == null ? "" : "( Order by " + this.Order +" ) ";
                    order = order == "" ? " " : order + (this.Desc == "Yes" ? " Desc) " : " Asc) ");
                    SqlComm = "SELECT TOP " + PageSize.ToString() + " * FROM  (   SELECT ROW_NUMBER() OVER" + this.Order + " AS RowNumber,* FROM " + this.entity.getTableName() + ") A WHERE RowNumber > " + (PageIndex - 1) * PageSize + " order by rowNumber"; ;
                    //SqlComm = iTop > 0 ? SqlComm.ToLower().Replace("select", "select top " + PageSize.ToString()) : SqlComm;
                    FL.SPL.ORM.ObjectMapper om = new SPL.ORM.ObjectMapper(this.entity);
                    om.SqlComm = SqlComm;
                    return om.DatatableToObject();
                }
                catch (System.Exception ex)
                {
                    return null;
                }
        }




        //public virtual System.Data.DataTable GetEntitysSplitPage()
        //{
        //    string SqlComm = string.Empty;
        //    try
        //    {
        //        string order = this.Order == "" || this.Order == null ? "" : "( Order by " + this.Order;
        //        order = order == "" ? " " : order + (this.Desc == "Yes" ? " Desc) " : " Asc) ");
        //        SqlComm = "SELECT TOP " + PageSize.ToString() + " * FROM  (   SELECT ROW_NUMBER() OVER" + this.Order + " AS RowNumber,* FROM " + this.entity.getTableName() + ") A WHERE RowNumber > " + (PageIndex - 1) * PageSize;
        //        //SqlComm = iTop > 0 ? SqlComm.ToLower().Replace("select", "select top " + PageSize.ToString()) : SqlComm;
        //        FL.SPL.ORM.ObjectMapper om = new SPL.ORM.ObjectMapper(this.entity);
        //        om.SqlComm = SqlComm;
        //        return om.);
        //    }
        //    catch (System.Exception ex)
        //    {
        //        return null;
        //    }
        //}

        /// <summary>
        /// 执行 Sql Command
        /// </summary>
        /// <param name="SqlCommand"></param>
        /// <returns></returns>
        public int RunSqlCommand(string SqlCommand)
        {
            return (new FL.DAL.DbSql()).ExecuteSqlTran(SqlCommand);
        }


        /// <summary>
        /// 执行 Sql Command
        /// </summary>
        /// <param name="SqlCommand"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public int RunSqlCommand(string SqlCommand, out string msg)
        {
            msg = "";
            try
            {
                return RunSqlCommand(SqlCommand);
            }
            catch(Exception e)
            {
                msg = "信息源:"+e.Source+"/r/n消息:"+e.Message;
                FL.Log.XTrace.WriteLine("-------------------------------SqlCommand Error---------------------------------");
                FL.Log.XTrace.WriteLine(msg);
                FL.Log.XTrace.WriteLine(SqlCommand);
                FL.Log.XTrace.WriteLine("-------------------------------SqlCommand Error---------------------------------");
               
                return -1;
            }
        }

        public DataSet RunProcedure(string storedProcName, IDataParameter[] parameters)
        {
            return (new DbSql()).RunProcedure(storedProcName, parameters,true);
        }

        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="storeProcName">存储过程</param>
        /// <param name="para">参数</param>
        /// <returns></returns>
        public FL.Lite.IResultSet RunProcedure(string storeProcName, object[] para)
        {
            FL.Lite.IResultSet _set = null;
            using (var db = FL.Lite.DBHelper.CreateDb(FL.DAL.ConnectionStringNames.OpenExpressApp))
            {
                _set = db.Exec(storeProcName, para);
            }
            return _set;
        }

        #region 相关属性
        public virtual int iTop
        {
            get;
            set;
        }

        public virtual string Order
        {
            get;
            set;
        }

        public virtual string Desc
        {
            get;
            set;
        }

        public virtual int PageIndex
        {
            get;
            set;
        }

        public virtual int PageSize
        {
            get;
            set;
        }
        #endregion

    }
}